import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Index",
    component: () => import("../home.vue"),
    meta: { title: "首页" },
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../login.vue"),
    meta: { title: "登录" },
  },
  {
    path: "/activity",
    name: "activity",
    component: () => import("../components/activityInfo.vue"),
  },
  {
    path: "/message",
    name: "message",
    component: () => import("../components/message.vue"),
  },
  {
    path: "/result",
    name: "result",
    component: () => import("../components/pages/middleScreening/result/result.vue"),
  },
  {
    path: "/mine",
    name: "mine",
    component: () => import("../components/mine.vue"),
  },
  // {
  //   path: "/index",
  //   name: "shouye",
  //   component: () => import("../components/pages/index/index.vue"),
  //   children: [
  //     {
  //       path: '/index/detail',
  //       name: 'detail',
  //       component: () => import('../components/pages/middleScreening/detail.vue'),
  //     },
  //   ]
  // },

];

const router = new VueRouter({
  routes,
  mode: "hash",
});

// 为路由对象 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的的路径
  // from 代表从哪个路径跳转
  // next 是一个函数 表示放行 next() 放行 next('/login') 强制跳转
  //如果用户访问的登录页面，直接放行
  // 获取存储token的开始时间
  const tokenStartTime = localStorage.getItem('tokenStartTime');
  if (tokenStartTime != undefined || tokenStartTime != null) {
    // 后台给出的token有效时间，一个星期 单位 是秒
    // 我们自己定义6天过期，让用户重新登录一下， 用户总不可能在一个页面挂机一天吧
    const timeOver = 6 * 24 * 3600 * 1000;
    // 当前时间
    let date = new Date().getTime();
    // 如果大于说明是token过期了
    if (date - tokenStartTime > timeOver) {
      localStorage.removeItem("token");
    }
  }
  if (to.path === '/login') return next()
  // 从sessionStorage中获取到保存的 token值
  const tokenStr = localStorage.getItem('token')
  //没有token 强制跳转到登录页
  if (!tokenStr) {
    return next('/login')
  }
  next()
})


export default router;
